package com.adams.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * File Name : VirtualPathUtil.java
 * 
 * @Description : 虚拟路径工具
 * @author 904370 张汉辉
 */
public class VirtualPathUtil
{
	private static Logger logger = Logger.getLogger(VirtualPathUtil.class
			.getName());

	private static String TOMCAT6_CONFIG_PATH = File.separatorChar + "conf"
			+ File.separatorChar + "Catalina" + File.separatorChar
			+ "localhost" + File.separatorChar;

	private static String JBOSS4_CONFIG_PATH = File.separatorChar + "conf"
			+ File.separatorChar + "jboss.web" + File.separatorChar
			+ "localhost" + File.separatorChar;

	private static String TOMCAT_PATH = System.getProperty("catalina.base");
	private static String JBOSS_PATH = System
			.getProperty("jboss.server.home.dir");

	private static String XML_FILE_PATH = "";
	private static boolean CONTAINER_SUPPORT_FLAG = false;

	static
	{
		if (StringUtils.isNotBlank(JBOSS_PATH))
		{
			XML_FILE_PATH = JBOSS_PATH + JBOSS4_CONFIG_PATH;
			CONTAINER_SUPPORT_FLAG = true;
		} else if (StringUtils.isNotBlank(TOMCAT_PATH))
		{
			XML_FILE_PATH = TOMCAT_PATH + TOMCAT6_CONFIG_PATH;
			CONTAINER_SUPPORT_FLAG = true;
		}
		if (XML_FILE_PATH.endsWith(File.separator))
		{
			XML_FILE_PATH = XML_FILE_PATH.substring(0, XML_FILE_PATH.length()
					- File.separator.length());
		}
	}

	/**
	 * Description : 设置容器虚拟路径
	 * 
	 * @param filepath
	 * @param virtualpath
	 * 
	 */
	public static void setVirtualPath(String filepath, String virtualpath)
	{
		if (CONTAINER_SUPPORT_FLAG)
		{
			try
			{
				File path = new File(XML_FILE_PATH);
				boolean pathexists = false;
				if (!path.exists())
				{
					pathexists = path.mkdirs();
				} else
				{
					pathexists = true;
				}

				if (!pathexists)
				{
					logger.error("创建" + XML_FILE_PATH + "路径失败!");
					return;
				}

				if (virtualpath.endsWith("/"))
				{
					virtualpath = virtualpath.substring(0,
							virtualpath.length() - 1);
				}
				String filename = StringUtils.replace(virtualpath, "/", "#");
				if (filename.startsWith("#"))
				{
					filename = filename.substring(1);
				}

				filename = filename + ".xml";
				File xmlFile = new File(XML_FILE_PATH + File.separator
						+ filename);

				Document document = null;
				if (!xmlFile.exists())
				{
					document = createVirtualPathXml(filepath, virtualpath);
				} else
				{
					SAXReader reader = new SAXReader();
					document = reader.read(xmlFile);
					document = updateVirtualPathXml(document, filepath,
							virtualpath);
				}

				FileOutputStream fout = new FileOutputStream(xmlFile, false);
				BufferedOutputStream bout = new BufferedOutputStream(fout);
				bout.write(document.asXML().getBytes("utf-8"));
				bout.close();
				fout.close();
			} catch (IOException e)
			{
				logger.error("读取文件" + XML_FILE_PATH + "出错!", e);
			} catch (DocumentException e)
			{
				logger.error("解析xml文件" + XML_FILE_PATH + "出错!", e);
			}
		}
	}

	/**
	 * Description : 移除容器虚拟路径
	 * 
	 * @param virtualpath
	 * 
	 */
	public static void removeVirtualPath(String virtualpath)
	{
		if (CONTAINER_SUPPORT_FLAG)
		{
			String filename = StringUtils.replace(virtualpath, "/", "#");
			if (filename.startsWith("#"))
			{
				filename = filename.substring(1);
			}

			filename = filename + ".xml";
			File xmlFile = new File(XML_FILE_PATH + filename);
			if (xmlFile.exists())
			{
				xmlFile.delete();
			}
		}
	}

	private static Document createVirtualPathXml(String filepath,
			String virtualpath)
	{
		Document document = DocumentHelper.createDocument();
		document.setXMLEncoding("UTF-8");
		Element context = document.addElement("Context");
		context.addAttribute("docBase", filepath);
		context.addAttribute("path", virtualpath);
		return document;
	}

	private static Document updateVirtualPathXml(Document document,
			String filepath, String virtualpath)
	{

		Element context = document.getRootElement();
		Attribute docBase = context.attribute("docBase");
		String oldfilepath = docBase.getValue();
		if (!oldfilepath.equals(filepath))
		{
			docBase.setValue(filepath);
		}
		Attribute path = context.attribute("path");
		String oldvirtualpath = path.getValue();
		if (!oldvirtualpath.equals(virtualpath))
		{
			path.setValue(virtualpath);
		}
		return document;
	}
}
